package com.stu.vertx.hello.controller;

import cn.hutool.core.util.StrUtil;
import com.stu.vertx.hello.utils.EncodeUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import static com.stu.vertx.hello.utils.ConvertUtils.decryptByBase64;
import static com.stu.vertx.hello.utils.ConvertUtils.netSourceToBase64;

/**
 * 文件上传与下载
 */
@RestController
@RequestMapping("/files")
public class FileController {

    @GetMapping("/test")
    public String test() {
        return "test ok";
    }

    /**
     * PDF下载
     *
     * @param response
     */
    @GetMapping("/file2")
    public void downPDF(HttpServletResponse response) {
        OutputStream os;  // 新建一个输出流对象
        String code = netSourceToBase64("https://www1.hkexnews.hk/listedco/listconews/sehk/2021/0901/2021090102155_c.pdf", "GET");
        System.out.println(code);
        try {
            if (StrUtil.isNotEmpty(code)) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/pdf;charset=UTF-8");
                // inline attachment
                response.addHeader("Content-Disposition","attachment; filename=" + "fileName.pdf");
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setDateHeader("Expires", 0);
                byte[] bytes = decryptByBase64(code);
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

    /**
     * PDF显示
     *
     * @param response
     */
    @GetMapping("/file1")
    public void showPDF(HttpServletResponse response) {
        OutputStream os;  // 新建一个输出流对象
        String code = netSourceToBase64("https://www1.hkexnews.hk/listedco/listconews/sehk/2021/0901/2021090102155_c.pdf", "GET");
        System.out.println(code);
        try {
            if (StrUtil.isNotEmpty(code)) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/pdf;charset=UTF-8");
                // response.addHeader("Content-Disposition","inline; filename=" + "fileName");
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setDateHeader("Expires", 0);
                byte[] bytes = decryptByBase64(code);
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件显示失败");
        }
    }

}
